package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 自动补货工单
 */
@Component
@Topic(TopicConfig.VMS_SUPPLY_TOPIC)
public class SupplyTaskHandler implements MsgHandler {
    @Autowired
    private TaskService taskService;

    @Autowired
    private VMService vmService;


    @Override
    public void process(String jsonMsg) throws IOException {
        //解析消息
        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        //创建TaskViewModel封装补货数据
        TaskViewModel taskViewModel = new TaskViewModel();
        taskViewModel.setInnerCode(supplyContract.getInnerCode());//设备编号
        taskViewModel.setCreateType(0);//创建类型
        taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);//工单类型
        taskViewModel.setDesc("自动补货工单");//备注
        //根据VMService得到区域id
        VmVO vmInfo = vmService.getVMInfo(supplyContract.getInnerCode());
        //根据taskService得到执行人id
        taskViewModel.setUserId(taskService.getLeastUser(vmInfo.getRegionId(),false));

        //遍历补货消息将其封装入TaskViewModel.setDetails
        List<TaskDetailsViewModel> taskDetailsViewModels = new ArrayList<>();
        List<SupplyChannel> supplyData = supplyContract.getSupplyData();
        for (SupplyChannel supplyDatum : supplyData) {
            TaskDetailsViewModel detailsViewModel = new TaskDetailsViewModel();
            detailsViewModel.setSkuName(supplyDatum.getSkuName());//商品姓名
            detailsViewModel.setSkuImage(supplyDatum.getSkuImage());//商品图片
            detailsViewModel.setSkuId(supplyDatum.getSkuId());//商品id
            detailsViewModel.setExpectCapacity(supplyDatum.getCapacity());//补货数量
            detailsViewModel.setChannelCode(supplyDatum.getChannelId());//货道编号
            taskDetailsViewModels.add(detailsViewModel);
        }

        taskViewModel.setDetails(taskDetailsViewModels);
        //创建补货工单
        taskService.createTask(taskViewModel);
    }
}
